package com.zhuoya.healthcard.util;

import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
    public static final String encode = "utf-8";

    public static String dealResponseResult(final InputStream inputStream) {
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final byte[] array = new byte[1024];
        try {
            while (true) {
                final int read = inputStream.read(array);
                if (read == -1) {
                    break;
                }
                byteArrayOutputStream.write(array, 0, read);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return new String(byteArrayOutputStream.toByteArray());
    }

    public static void postCallBack(final String s, final JSONObject jsonObject, final HttpCallback httpCallback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                httpCallback.calllBack(HttpUtil.submitPostData(s, jsonObject, "utf-8"));
            }
        }).start();
    }

    public static String submitPostData(String string, final JSONObject jsonObject, final String s) {
        try {
            final byte[] bytes = jsonObject.toJSONString().getBytes(s);
            final HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(string).openConnection();
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            httpURLConnection.getOutputStream().write(bytes);
            final int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                return dealResponseResult(httpURLConnection.getInputStream());
            }
            final StringBuilder sb = new StringBuilder();
            sb.append("{\n  \"msg\": \"服务器错误,http状态码为");
            sb.append(responseCode);
            sb.append("\",\n  \"code\": 505\n}");
            string = sb.toString();
            return string;
        } catch (IOException ex2) {
            ex2.printStackTrace();
            return "{\n  \"msg\": \"网络错误\",\n  \"code\": 505\n}";
        } catch (Exception ex) {
            ex.printStackTrace();
            return "{\n  \"msg\": \"网络错误\",\n  \"code\": 505\n}";
        }
    }
}